<template>
  <div class="alert-management">
    <h1>提醒管理</h1>

    <div class="controls">
      <button @click="showCreateModal = true" class="btn-add">
        <i class="icon-plus"></i> 新增提醒
      </button>

      <div class="filter-controls">
        <select v-model="statusFilter" @change="fetchAlerts">
          <option value="all">所有状态</option>
          <option value="active">仅有效</option>
          <option value="inactive">仅已关闭</option>
        </select>

        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索标题或内容..."
          @input="handleSearch"
        />
      </div>
    </div>

    <!-- 提醒列表 -->
    <div class="alerts-table-container">
      <table class="alerts-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>标题</th>
            <th>内容</th>
            <th>提醒时间</th>
            <th>重复规则</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="alert in filteredAlerts" :key="alert.id">
            <td>{{ alert.id }}</td>
            <td>{{ alert.title }}</td>
            <td class="alert-content">{{ truncateText(alert.content, 50) }}</td>
            <td>{{ formatTime(alert.alert_time) }}</td>
            <td>{{ formatRepeatRule(alert.repeat) }}</td>
            <td>
              <span class="status-badge" :class="alert.is_active ? 'active' : 'inactive'">
                {{ alert.is_active ? "有效" : "已关闭" }}
              </span>
            </td>
            <td class="actions">
              <button
                @click="toggleAlertStatus(alert)"
                class="btn-toggle"
                :title="alert.is_active ? '关闭提醒' : '启用提醒'"
              >
                {{ alert.is_active ? "关闭" : "启用" }}
              </button>
              <button @click="editAlert(alert)" class="btn-edit">编辑</button>
              <button @click="deleteAlert(alert.id)" class="btn-delete">删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="filteredAlerts.length === 0 && !isLoading" class="no-alerts">
        没有找到符合条件的提醒
      </div>

      <div v-if="isLoading" class="loading">
        加载中...
      </div>
    </div>

    <!-- 新增/编辑提醒弹窗 -->
    <div class="modal-backdrop" v-if="showCreateModal || showEditModal" @click="closeModal"></div>
    <div class="modal" v-if="showCreateModal || showEditModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ showEditModal ? "编辑提醒" : "新增提醒" }}</h2>
          <button class="modal-close" @click="closeModal">&times;</button>
        </div>

        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="title">标题 <span class="required">*</span></label>
            <input
              type="text"
              id="title"
              v-model="form.title"
              required
              placeholder="输入提醒标题"
              maxlength="100"
            />
          </div>

          <div class="form-group">
            <label for="content">内容 <span class="required">*</span></label>
            <textarea
              id="content"
              v-model="form.content"
              required
              placeholder="输入提醒内容"
              rows="4"
            ></textarea>
          </div>

          <div class="form-group">
            <label for="alertTime">提醒时间 <span class="required">*</span></label>
            <input
              type="datetime-local"
              id="alertTime"
              v-model="form.alertTime"
              required
            />
          </div>

          <div class="form-group">
            <label for="repeat">重复规则</label>
            <select id="repeat" v-model="form.repeat">
              <option value="none">不重复</option>
              <option value="daily">每日重复</option>
              <option value="weekly">每周重复</option>
            </select>
          </div>

          <div class="form-actions">
            <button type="button" @click="closeModal" class="btn-cancel">取消</button>
            <button type="submit" class="btn-submit">
              {{ showEditModal ? "更新提醒" : "创建提醒" }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";

// API基础路径
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

// 状态管理
const alerts = ref([]);
const isLoading = ref(false);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const statusFilter = ref("all");
const searchQuery = ref("");

// 表单数据
const form = ref({
  title: "",
  content: "",
  alertTime: "",
  repeat: "none",
  id: null,
});

// 格式化重复规则
const formatRepeatRule = (rule) => {
  const rules = {
    "none": "不重复",
    "daily": "每日",
    "weekly": "每周"
  };
  return rules[rule] || rule;
};

// 格式化时间
const formatTime = (timeString) => {
  const date = new Date(timeString);
  return date.toLocaleString();
};

// 截断文本
const truncateText = (text, length) => {
  if (text.length <= length) return text;
  return text.substring(0, length) + "...";
};

// 获取所有提醒
const fetchAlerts = async () => {
  try {
    isLoading.value = true;
    let url = `${API_BASE_URL}/api/alerts`;

    // 添加状态过滤
    if (statusFilter.value !== "all") {
      url += `?is_active=${statusFilter.value === "active" ? "true" : "false"}`;
    }

    const response = await axios.get(url);
    alerts.value = response.data;
  } catch (error) {
    console.error("加载提醒失败:", error);
    alert("加载提醒失败，请重试");
  } finally {
    isLoading.value = false;
  }
};

// 过滤提醒列表
const filteredAlerts = computed(() => {
  if (!searchQuery.value) return alerts.value;

  const query = searchQuery.value.toLowerCase();
  return alerts.value.filter(alert =>
    alert.title.toLowerCase().includes(query) ||
    alert.content.toLowerCase().includes(query)
  );
});

// 搜索处理
const handleSearch = (e) => {
  // 延迟搜索以避免频繁过滤
  clearTimeout(window.searchTimeout);
  window.searchTimeout = setTimeout(() => {
    // 过滤由computed自动处理
  }, 300);
};

// 提交表单（新增或编辑）
const handleSubmit = async () => {
  try {
    // 转换时间格式（local datetime-local → UTC）
    const alertTime = new Date(form.value.alertTime).toISOString();

    const alertData = {
      title: form.value.title,
      content: form.value.content,
      alert_time: alertTime,
      repeat: form.value.repeat,
    };

    if (showEditModal.value) {
      // 编辑提醒
      await axios.put(`${API_BASE_URL}/api/alerts/${form.value.id}`, alertData);
      alert("提醒已更新");
    } else {
      // 新增提醒
      await axios.post(`${API_BASE_URL}/api/alerts`, alertData);
      alert("提醒已创建");
    }

    closeModal();
    fetchAlerts(); // 重新加载列表
  } catch (error) {
    console.error("提交提醒失败:", error);
    alert("提交失败，请重试");
  }
};

// 编辑提醒
const editAlert = (alert) => {
  // 转换UTC时间为local datetime-local格式
  const localTime = new Date(alert.alert_time).toISOString().slice(0, 16);

  form.value = {
    id: alert.id,
    title: alert.title,
    content: alert.content,
    alertTime: localTime,
    repeat: alert.repeat,
  };
  showEditModal.value = true;
};

// 切换提醒状态（启用/关闭）
const toggleAlertStatus = async (alert) => {
  try {
    const newStatus = !alert.is_active;
    await axios.put(`${API_BASE_URL}/api/alerts/${alert.id}`, {
      is_active: newStatus
    });
    alert(`提醒已${newStatus ? "启用" : "关闭"}`);
    fetchAlerts();
  } catch (error) {
    console.error("更新提醒状态失败:", error);
    alert("操作失败，请重试");
  }
};

// 删除提醒
const deleteAlert = async (alertId) => {
  if (confirm("确定要删除这个提醒吗？此操作不可撤销。")) {
    try {
      await axios.delete(`${API_BASE_URL}/api/alerts/${alertId}`);
      alert("提醒已删除");
      fetchAlerts();
    } catch (error) {
      console.error("删除提醒失败:", error);
      alert("删除失败，请重试");
    }
  }
};

// 关闭弹窗
const closeModal = () => {
  showCreateModal.value = false;
  showEditModal.value = false;
  form.value = {title: "", content: "", alertTime: "", repeat: "none", id: null};
};

// 页面加载时获取提醒列表
onMounted(() => {
  // 设置默认时间为当前时间加5分钟
  const defaultTime = new Date();
  defaultTime.setMinutes(defaultTime.getMinutes() + 5);
  form.value.alertTime = defaultTime.toISOString().slice(0, 16);

  fetchAlerts();
});
</script>

<style scoped>
.alert-management {
  max-width: 1200px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
  flex-wrap: wrap;
  gap: 15px;
}

.btn-add {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-add:hover {
  background-color: #359e75;
}

.icon-plus::before {
  content: "+";
  font-weight: bold;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

.filter-controls select,
.filter-controls input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-controls select {
  width: 150px;
}

.filter-controls input {
  min-width: 200px;
  width: 300px;
}

.alerts-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.alerts-table {
  width: 100%;
  border-collapse: collapse;
}

.alerts-table th,
.alerts-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #f1f1f1;
}

.alerts-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.alert-content {
  max-width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.status-badge.active {
  background-color: #eafaf1;
  color: #27ae60;
}

.status-badge.inactive {
  background-color: #fdedeb;
  color: #e74c3c;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-toggle,
.btn-edit,
.btn-delete {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  transition: background-color 0.3s;
}

.btn-toggle {
  background-color: #f39c12;
  color: white;
}

.btn-toggle:hover {
  background-color: #d35400;
}

.btn-edit {
  background-color: #3498db;
  color: white;
}

.btn-edit:hover {
  background-color: #2980b9;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-delete:hover {
  background-color: #c0392b;
}

.no-alerts {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

.loading {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1001;
  width: 100%;
  max-width: 500px;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: #2c3e50;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #7f8c8d;
}

form {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
  font-weight: 500;
}

.required {
  color: #e74c3c;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 25px;
}

.btn-cancel,
.btn-submit {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #7f8c8d;
  border: 1px solid #ddd;
}

.btn-cancel:hover {
  background-color: #eaeaea;
}

.btn-submit {
  background-color: #3498db;
  color: white;
  border: none;
}

.btn-submit:hover {
  background-color: #2980b9;
}
</style>
